import { CommonForm } from '@/pages/OrderModule/common/components/CommonForm';
import { CommonModal } from '@/pages/OrderModule/common/components/CommonModal';
import SubTitle from '@/pages/OrderModule/common/components/SubTitle';
import Typography from '@/pages/OrderModule/common/components/Typography';
import { Col, Form, Radio, Row, Modal, message } from 'antd';
import OrderAreaRadioGroup from '../../components/OrderAreaRadioGroup1';
import OrderNumberCount from '../../components/OrderNumberCount';
import { useState, useEffect, useMemo, useRef } from 'react';
import { queryAllWarehouse, modifyWarehouseOp } from '../../../../services';
import CommonLoading from '@/components/CommonLoading';
import { find } from 'lodash';
import { getCurrentUser } from '@/utils/authority';

/** 批量选择发货仓 */
function SelectShippingWarehouseModal(props) {
  const [form] = Form.useForm();

  const [warehouseList, setWarehouseList] = useState([]);
  const [loading, setLoading]=useState(false);
  const [showNumber, setShowNumber] = useState({});
  const filterIds = useRef(undefined);

  const { orderList, searchForm, selectKeys } = props;

  const currentUuid = useMemo(() => {
    return getCurrentUser()?.uuid;
  }, [])

  useEffect(()=>{
    getWarehouseList();
  }, [])

  //发货仓列表数据
  const getWarehouseList = async () => {
    const { success, data = [] } = await queryAllWarehouse();
    if (success) {
      setWarehouseList(data.map(item=>{
        const warehouseName = `${item.warehouseName}（${item.isOpen ? '代发' : '自发'}）`;
        return ({
          ...item,
          label: item.state === 0 ?  warehouseName :  (
            <>
             {warehouseName} <Typography type="error">（已禁用）</Typography>
            </>
          ),
          value: item.id
        })
      }));
    }
  }

  function handleOk() {
    const { warehouseId } = form.getFieldsValue();
    if(!warehouseId){
      return message.info('请先选择发货仓');
    }
    handleSave(warehouseId);
  }

  const handleSave = async (warehouseId) => {
    let params = { ids: filterIds.current, operationPage: props.operationPage == 'sysOrder' ? 2 : 3 };
    if(warehouseId != 0){
      const { warehouseName, state: warehouseState, type: warehouseType, uuid: warehouseUuid  } = find(warehouseList, ['id', warehouseId]);
      if(warehouseState){
        return message.info('已禁用的仓库无法选择');
      }
      params = {
        ...params,
        warehouseId,
        warehouseName,
        warehouseState,
        warehouseType,
        warehouseUuid,
      }
    }
    setLoading(true);
    const { msg, success } = await modifyWarehouseOp(params);
    setLoading(false);
    if(success){
      props.handleOk(1, filterIds.current);
      if(msg != '操作成功'){
        Modal.info({
          title:'修改发货仓提示',
          content: msg
        })
      }else{
        message.success(msg);
      }
    }
  }

  function WarehouseRadioGroup(props) {
    const { options, ...args } = props;
    return (
      <Radio.Group {...args}>
        <Row>
          <Col style={{ marginTop: 12 }} span={24}>
            <Radio value="0">暂不选择发货仓</Radio>
          </Col>
          {options.map((item) => {
            return (
              <Col style={{ marginTop: 12 }} key={item.value} span={12}>
                <Radio value={item.value}>{item.label}</Radio>
              </Col>
            );
          })}
        </Row>
      </Radio.Group>
    );
  }

  const orderAreaRadioProps = {
    searchForm,
    selectKeys,
    orderList,
    states: [10, 30],
    title:'仅限待审核、异常状态订单',
    updateShowNumer(obj, ids){
      filterIds.current = ids;
      setShowNumber(obj);
    }
  }

  return (
    <CommonModal title={{ title: '批量选择发货仓' }} open={true} width="530px" onOk={handleOk} onCancel={props.handleCancel}>
      <CommonForm
        formProps={{
          form,
        }}
        columns={[
          {
            name: 'radio-group',
            slot: <OrderAreaRadioGroup {...orderAreaRadioProps} />,
          },
          {
            block: (
              <>
                <OrderNumberCount
                  data={[
                    { label: '待审核', value: showNumber[10], type: 'warning' },
                    { label: '异常', value: showNumber[30], type: 'error' },
                  ]}
                />
                <SubTitle symbol as="s2" title="发货仓" extraText="（修改发货仓，快递默认清空）" wrapStyle={{ marginTop: 16 }} />
              </>
            ),
          },
          {
            name: 'warehouseId',
            slot: (
              <WarehouseRadioGroup
                options={warehouseList}
              />
            ),
            rules:[{required: true, message: '请先选择仓库'}]
          },
        ]}
      ></CommonForm>
      <CommonLoading loading={loading} />
    </CommonModal>
  );
}

export default SelectShippingWarehouseModal;
